#include "ringQueue.hpp"

char op[4] = {'+','-','*','/'};

int calculate(int x,int y,char op)
{
    switch(op)
    {
        case '+' : return x + y;
        break;
        case '-' : return x - y;
        break;
        case '*' : return x * y;
        break;
        case '/' : return x / y;
        break;
    }
}

//生产者
void* productor(void* args)
{
    RingQueue<Task>* rq = (RingQueue<Task>*)args;
    while(true)
    {
        // static int x = 10;
        int x = rand() % 10;
        int y = rand() % 10;
        int i = rand() % 4;
        Task task(x,y,op[i],calculate);
        rq->Push(task);
        // std::cout << "生产: " << x << std::endl;
        std::cout <<"生产: " << x << op[i] << y << "=?" << std::endl;
        // x += 1;
        sleep(1);
    }
}  

//消费者
void* consumer(void* args)
{
    RingQueue<Task>* rq = (RingQueue<Task>*)args;
    while(true)
    {
        // int ret;
        Task task;
        rq->Pop(task);
        // std::cout << "消费: " << ret << std::endl;
        std::cout << "消费: 计算结果= " << task() << std::endl;
        sleep(5);
    }
}

int main()
{
    srand(time(nullptr) ^ getpid());
    RingQueue<Task>* rq = new RingQueue<Task>;
    pthread_t c,p;
    pthread_create(&c,nullptr,consumer,(void*)rq);
    pthread_create(&p,nullptr,productor,(void*)rq);

    pthread_join(c,nullptr);
    pthread_join(p,nullptr);

    return 0;
}